package com.ledim.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import com.ledim.activity.base.LeDimBaseActivity;
import com.ledim.adapter.SearchRecordAdapter;
import com.ledim.bean.ChatRoomBean;
import com.ledim.bean.LedimSearchRecord;
import com.ledim.db.LedimDBManager;
import com.ledim.fragment.CommonDialogFragment;
import com.ledim.itf.LedimDialogClickListner;
import com.ledim.itf.LedimSearchInterface;
import com.ledim.ledimview.SearchBarView;
import com.ledim.utils.ConstantUtil;
import com.letv.android.young.client.R;
import java.util.ArrayList;
import java.util.List;

/**
 * 搜索首页
 */
public class SearchActivity extends LeDimBaseActivity implements LedimSearchInterface {

    public static final String ADD_PLAY = "add_play";
    public static final String ROOM_ID = "room_id";
    private GridView mRecordsGridView;
    private SearchRecordAdapter mRecordsAdapter;
    private View mRecordLayout;
    private View mRecordWorkLayout;
    private View mNoSearchRecord;
    private TextView mDeleteRecord;
    private SearchBarView mSearchView;
    private ImageView mCancel;
    private boolean mAddPlay;
    private ChatRoomBean mRoom;
    private TextView mAddTitle;
    private TextView mAddFinish;
    private ArrayList<String> mRecords = new ArrayList<String>();
    private List<LedimSearchRecord> mLedimSearchRecords = new ArrayList<LedimSearchRecord>();
    private CommonDialogFragment mClearSearchDialog;


    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_search;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshSearchRecord();
    }

    private void initView() {
        mAddPlay = getIntent().getBooleanExtra(ADD_PLAY, false);
        mRoom = (ChatRoomBean) getIntent().getSerializableExtra(ROOM_ID);
        mRecordsGridView = (GridView) findViewById(R.id.search_record_gridview);
        mDeleteRecord = (TextView) findViewById(R.id.search_record_delete);
        mRecordLayout = findViewById(R.id.search_record_layout);
        mRecordWorkLayout = findViewById(R.id.search_record_work_layout);
        mNoSearchRecord = findViewById(R.id.no_search_record);
        mSearchView = (SearchBarView) findViewById(R.id.search_view);
        mCancel = (ImageView) findViewById(R.id.search_cancel);
        mAddTitle = (TextView) findViewById(R.id.add_title);
        mAddFinish = (TextView) findViewById(R.id.add_finish);

        mCancel.setOnClickListener(this);
        mDeleteRecord.setOnClickListener(this);
        mAddFinish.setOnClickListener(this);
        if (mAddPlay) {
            mAddTitle.setText("添加到放映单");
        } else {
            mAddTitle.setText("搜索");
        }
        mSearchView.bindData(null, this);
    }

    /**
     * 刷新历史搜索
     */
    private void refreshSearchRecord() {
        mSearchView.setListViewSuggestedGone();
        mRecordWorkLayout.setVisibility(View.VISIBLE);
        try {
            //从数据库中读取搜索的历史记录,显示最新5条历史搜索

            mLedimSearchRecords = LedimDBManager.getInstance()
                                                .getDaoSession()
                                                .getLedimSearchRecordDao()
                                                .queryBuilder()
                                                .limit(10)
                                                .build()
                                                .list();
            //历史记录为空时不显示历史记录
            if (mLedimSearchRecords.size() == 0) {
                mRecordLayout.setVisibility(View.GONE);
                mNoSearchRecord.setVisibility(View.VISIBLE);
            } else {
                mRecordLayout.setVisibility(View.VISIBLE);
                mNoSearchRecord.setVisibility(View.GONE);
                mRecords.clear();
                for (int i = 0; i < mLedimSearchRecords.size(); i++) {
                    mRecords.add(mLedimSearchRecords.get(i).keyword);
                }
                if (mRecordsAdapter == null) {
                    mRecordsAdapter = new SearchRecordAdapter(this, mRecords);
                    mRecordsGridView.setAdapter(mRecordsAdapter);
                } else {
                    mRecordsAdapter.notifyDataSetChanged();
                }
                mRecordsGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position,
                                            long id) {
                        if (position < mLedimSearchRecords.size()) {
                            Intent intent =
                                    new Intent(SearchActivity.this, SearchResultActivity.class);
                            intent.putExtra(SearchResultActivity.KEYWORD, mLedimSearchRecords.get(position).keyword);
                            intent.putExtra(SearchResultActivity.ADD_PLAY, mAddPlay);
                            intent.putExtra(SearchResultActivity.ROOM_ID, mRoom);
                            startActivityForResult(intent, 0);
                        }
                    }
                });
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search_record_delete:
                showClearDialog();
                break;
            case R.id.search_cancel:
                finish();
                break;

        }
    }

    /**
     * 二次确认弹窗
     */
    private void showClearDialog() {
        String hint = "真是叫人不好意思啊,\n这些黑历史还是快点翻页吧？";
        if (mClearSearchDialog == null) {
            mClearSearchDialog =
                    CommonDialogFragment.getInstance(ConstantUtil.DialogConstant.DIALOG_HORIZONTAL_TYPE, hint, "翻页", "不翻", new LedimDialogClickListner() {
                        @Override
                        public void onClickPositive(View view) {
                            //清空搜索历史纪录数据库
                            LedimDBManager.getInstance()
                                          .getDaoSession()
                                          .getLedimSearchRecordDao()
                                          .deleteAll();
                            mRecords.clear();
                            mRecordsAdapter.notifyDataSetChanged();
                            mRecordLayout.setVisibility(View.GONE);
                            mNoSearchRecord.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onClickNegative(View view) {

                        }

                        @Override
                        public void onDismiss() {

                        }
                    });
        }
        mClearSearchDialog.showDialog(getSupportFragmentManager());

    }

    @Override
    public void notifyViewVisible(int visible) {
        mRecordWorkLayout.setVisibility(visible);
    }

    @Override
    public void doSearch(String word) {
        Intent intent = new Intent(this, SearchResultActivity.class);
        intent.putExtra(SearchResultActivity.KEYWORD, word);
        intent.putExtra(SearchResultActivity.ADD_PLAY, mAddPlay);
        intent.putExtra(SearchResultActivity.ROOM_ID, mRoom);
        startActivityForResult(intent, 0);
        LedimSearchRecord record = new LedimSearchRecord();
        record.keyword = word;
        record.time = System.currentTimeMillis();
        LedimDBManager.getInstance()
                      .getDaoSession()
                      .getLedimSearchRecordDao()
                      .insertOrReplaceInTx(record);
    }

    @Override
    public boolean autoShowKeyBoard() {
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            finish();
        }
    }
}
